package com.qf.filter;

import com.qf.bean.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 19/11/2019
 * Echo
 * qmxc
 * Alibaba
 */
public class LoginFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        String uri = request.getRequestURI();
        Employee user = (Employee)session.getAttribute("user");
        if (user!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            if (uri.endsWith("/login.jsp")||uri.endsWith("/login")||uri.equals("/")||uri.contains("/css/")||uri.contains("img")||uri.endsWith("/favicon.ico")){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                response.getWriter().print("<script>alert('请先登录再访问');location.href='login.jsp';</script>");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
